/**
 *
 * Copyright 2009 garrett
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License.  You may obtain a copy of the
 * License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License. 
 */
package org.memesis.pandorasbook;

import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JDesktopPane;

/**
 * Subclasses JDesktopPane to add additional functionality.
 *
 * @author garrett
 */
@SuppressWarnings("serial")
public class PandoraDesktopPane extends JDesktopPane {
	private Image backgroundImage = null;
	
	public PandoraDesktopPane() {
	}
	
	public void setBackgroundImage(URL imageUrl) throws IOException {
		backgroundImage = ImageIO.read(imageUrl);
		repaint();
	}
	
	public void setBackgroundImage(String imageUrl) throws IOException {
		setBackgroundImage(new URL(imageUrl));
	}

	/* (non-Javadoc)
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if(backgroundImage != null) {
			tileImage(g);
		}
	}
	
	private void tileImage(Graphics g) {
		int imageWidth = backgroundImage.getWidth(this);
		int imageHeight = backgroundImage.getHeight(this);
		
		// By default, we tile the image across the desktop
		if(imageWidth > 0 && imageHeight > 0) {
			for(int y = 0; y < getHeight(); y += imageHeight) {
				for(int x = 0; x < getWidth(); x += imageWidth) {
					g.drawImage(backgroundImage, x, y, this);
				}				
			}
		}		
	}
}